package cn.melonlib.record.oper.model.view;

import cn.hutool.core.bean.BeanUtil;
import cn.melonlib.cores.model.anno.ModelComment;
import cn.melonlib.objects.maps.JsonMap;
import cn.melonlib.record.oper.model.entity.OperationRecord;
import cn.melonlib.record.oper.model.entity.OperationRecordIndex;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.EqualsAndHashCode;

import java.util.List;
import java.util.Map;

@Data
@EqualsAndHashCode(callSuper = true)
@ModelComment("日志信息")
public class OperationRecordView extends OperationRecordIndex {


    public OperationRecordView(OperationRecord operationRecord,ObjectMapper objectMapper){
        BeanUtil.copyProperties(operationRecord,this,"params","result","extendsInfo");
        try{
            this.params=objectMapper.readValue(operationRecord.getParams(), new TypeReference<Map<String, Object>>() {
            });
        }catch (Exception e){
            this.params= JsonMap.createMap().append("error",operationRecord.getParams());
        }

        try{
            String result=operationRecord.getResult();
            if(result.startsWith("[")){
                this.result=objectMapper.readValue(result, new TypeReference<List<Map<String,Object>>>() {
                });
            }else{
                this.result=objectMapper.readValue(result, new TypeReference<Map<String,Object>>() {
                });
            }
        }catch (Exception e){
            this.result=operationRecord.getResult();
        }

        try {
            this.extendsInfo = objectMapper.readValue(operationRecord.getExtendsInfo(), new TypeReference<Map<String, Object>>() {
            });
        }catch (Exception e){
            this.extendsInfo=JsonMap.createMap().append("error",operationRecord.getExtendsInfo());
        }
        this.recordTypeName=operationRecord.getRecordType().getLabel();
    }

    @ModelComment("输入参数")
    private Map<String, Object> params;

    @ModelComment("返回结果")
    private Object result;

    @ModelComment("扩展记录信息")
    private Map<String,Object> extendsInfo;

    @ModelComment("名称")
    private String recordTypeName;
}
